from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin
from admin.utils.page import Mypage
from system.serializer.job import JobSerializer, CreateJobSerializer, UpdateJobSerializer
from system.models import Job
from django_filters.rest_framework import DjangoFilterBackend


class JobView(GenericViewSet, ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin):
    queryset = Job.objects.filter(is_delete=False).order_by('id')
    serializer_class = JobSerializer
    pagination_class = Mypage
    filter_backends = [DjangoFilterBackend, ]
    filter_fields = ['name','enabled']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context = {'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(serializer.data)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object(request)
        serializer = self.get_serializer(instance, data=request.data, partial=partial, context={'request':request})
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_del_object(request)
        for i in instance:
            self.perform_destroy(i)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def get_del_object(self, request):      # 单个删除或批量删除
        id_list = request.data
        job_list = []
        for id in id_list:
            job_list.append(Job.objects.filter(pk=id))
        return job_list

    def perform_destroy(self, instance):
        instance.update(is_delete=True)

    def get_object(self, request):
        pk = request.data.get('id')
        return Job.objects.filter(pk=pk).first()

    def get_serializer_class(self):
        if self.action == 'create':
            return CreateJobSerializer
        elif self.action == 'list':
            return JobSerializer
        elif self.action == 'update':
            return UpdateJobSerializer


